from fastapi import APIRouter, Depends, Security
from pydantic import UUID4
from tortoise.expressions import Q
from core.auth import check_access, get_current_user
from core.logger import logger
from curd.user_curd import ctrl_family, ctrl_user, ctrl_user_ralation
from schemas.base_schema import Success, Fail
from schemas.user_schema import FamilyBase, FamilyOut, UserAddMember, UserBaseOut
from settings import settings

router = APIRouter()

@router.post("/create", dependencies=[Security(check_access, scopes=["family"])])
async def create_family(req: FamilyBase, me=Depends(get_current_user)):
    if me.username == "admin":
        family_obj = await ctrl_family.create(req)
        logger.debug("Family Create Successful!")
        return family_obj
    else:
        if not me.family:
            family_obj = await ctrl_family.create(req)
            me.family = family_obj
            await me.save()
            logger.debug("Family Create Successful!")
            return family_obj
        else:
            return Fail(data="You can,t do it")
        

@router.post("/add_member", response_model=FamilyOut, dependencies=[Security(check_access, scopes=["family"])])
async def add_member(req: UserAddMember, me=Depends(get_current_user)):
    family_obj = await ctrl_family.get(family_id=str(req.family_id))
    if req.is_create:
        user_obj = await ctrl_user.create(req.is_create)
    else:
        user_obj = await ctrl_user.get(username=req.username)
    user_obj.family = family_obj
    await user_obj.save()
    logger.debug("Family Add_member Successful!")
    return family_obj

@router.get("/get_family", response_model=FamilyOut, dependencies=[Security(check_access, scopes=["base"])])
async def get_family(family_id: UUID4=None, me=Depends(get_current_user)):
    family_obj = None
    if me.username == "admin":
        family_obj = await ctrl_family.get_with_users(family_id)
        logger.debug("Family GET Successful!")
    else:
        if me.family.family_id == family_id:
            family_obj = await ctrl_family.get_with_users(family_id)
            logger.debug("Family GET Successful!")
    if family_obj:
        family_data = {k : getattr(family_obj, k, None) for k in ctrl_family.get_model_fields()}
        family_data["members"] = [member for member in family_obj.members.related_objects]
        return family_data
    return Fail(data="You can,t do it")